package com.pet.item.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pet.api.dto.ItemDTO;
import com.pet.common.domain.PageDTO;
import com.pet.common.domain.Result;
import com.pet.item.domain.po.Video;
import com.pet.item.domain.query.VideoQuery;
import com.pet.item.domain.vo.VideoDetailVO;
import com.pet.item.mapper.VideoMapper;
import com.pet.item.service.IItemService;
import com.pet.item.service.IVideoService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 视频表 服务实现类
 * </p>
 *
 * @author Cookies
 * @since 2024-07-11
 */
@Service
@RequiredArgsConstructor
public class VideoServiceImpl extends ServiceImpl<VideoMapper, Video> implements IVideoService {
    private final IItemService itemService;

    @Override
    public Result addVideo2Item(Video video) {
        // 检测商品是否已关联视频
        Integer count = lambdaQuery()
                .eq(Video::getItemId, video.getItemId())
                .count();
        if (count > 0) {
            return Result.error("商品已关联视频");
        }
        boolean isSucceed = save(video);
        return isSucceed ? Result.success() : Result.error();
    }

    @Override
    public PageDTO<VideoDetailVO> getVideoList(VideoQuery videoQuery) {
        Page<Video> page = new Page<>(videoQuery.getPageNo(), videoQuery.getPageSize());
        lambdaQuery()
                .like(StrUtil.isNotBlank(videoQuery.getKeyWord()), Video::getVideo, videoQuery.getKeyWord())
                .page(page);
        PageDTO<VideoDetailVO> pageDTO = PageDTO.of(page, VideoDetailVO.class);
        if (CollUtil.isNotEmpty(pageDTO.getList())) {
            handlePageDTO(pageDTO);
        }
        return pageDTO;
    }

    private void handlePageDTO(PageDTO<VideoDetailVO> pageDTO) {
        List<VideoDetailVO> list = pageDTO.getList();

        // 获取商品id
        List<Integer> itemIds = list.stream().map(VideoDetailVO::getItemId).collect(Collectors.toList());
        List<ItemDTO> items = itemService.getItemByIds(itemIds);
        if (CollUtil.isEmpty(items)) {
            return;
        }
        // 转为id到item的map
        Map<Integer, ItemDTO> itemMap = items.stream().collect(Collectors.toMap(ItemDTO::getId, Function.identity()));
        // 写入vo
        for (VideoDetailVO vo : list) {
            ItemDTO item = itemMap.get(vo.getItemId());
            if (item == null) {
                continue;
            }
            vo.setItemName(item.getTitle());
        }
        pageDTO.setList(list);
    }
}
